local helper=require 'library.helpers'
local registry=require ('vanilla.v.registry'):new('application')
local cache=require('library.cache'):new()
local db=require 'models.db'

local ConfigModule = {}

function ConfigModule:new()
	local o=registry:get('config')
	if not o then
		o = {
			default={
				blog_name={value='Clive\'s blog',type='text',comments="blog 名称"},
				index_cache={value='30',type='text',comments="首页缓存时间,单位秒,0不设置"},
				article_cache={value='30',type='text',comments="文章详细页缓存时间,单位秒,0不设置"},
				footer={value='© by Clive powered by vanilla',type='text',comments="底部版权"},
			},
			user={}
		}

		setmetatable(o,{__index=self})
		o:_init()
		registry:set('config',o)
	end

	return o
end

function ConfigModule:get_default()
	return self.default
end

function ConfigModule:get(k)
	if helper:table_key_exist(k,self.default) then
		local val=self.user[k] or self.default[k].value
		return val
	end
	return nil
end

function ConfigModule:set(k,val)
	if helper:table_key_exist(k,self.default) then
		self.user[k]=val
		return true
	end
	helper:raise_syserror('not found this config')
end

function ConfigModule:save()
	local config= db:new('config')
	for i,v in pairs(self.user) do
		local row={
			['key']=i,
			['value']=v,
			['type']=self.default[i]['type'],
			['comments']=self.default[i]['comments'],
		}
		config:replace(row)
	end
end

function ConfigModule:_init()
	local config= db:new('config')
	local rows=config:get_list()
	for i,v in ipairs(rows) do
		self.user[v['key']]=v['value']
	end
end

return ConfigModule